<template>
  <view class="product">
    <view class="product-top">
      <view class="search mb-10">
        <view class="search-left" @click="onScanCode">
          <up-icon name="scan" size="24" color="#44bdf1"></up-icon>
        </view>
        <up-input
          placeholder="搜索商品名称/条形码"
          border="none"
          v-model="keyword"
          confirmType="search"
          @confirm="getProductData"
          @clear="onSearch"
          clearable
        ></up-input>
      </view>
      <my-filterbar
        v-model:price="priceSort"
        v-model:number="numberSort"
        @filter="popupShow = true"
      ></my-filterbar>
    </view>

    <view class="product-main">
      <view class="product-list">
        <view
          class="product-item"
          v-for="(item, index) in productList"
          :key="index"
        >
          <my-goods :data="item" @click="handleToGoodsDetail(item)"></my-goods>
        </view>
      </view>
      <up-loadmore
        v-if="productList.length > 0"
        bg-color="rgb(240, 240, 240)"
        :status="loadStatus"
      ></up-loadmore>
      <my-empty v-else type="search"></my-empty>
    </view>

    <up-popup :show="popupShow" mode="right" @close="onMoreFilter">
      <view class="popup-main">
        <view class="popup-filter">
          <view class="popup-title">价格</view>
          <view class="popup-filter-price">
            <up-input
              type="number"
              placeholder="最低价"
              border="surround"
              inputAlign="center"
              v-model="minPrice"
            ></up-input>
            <view class="line"></view>
            <up-input
              type="number"
              placeholder="最高价"
              border="surround"
              inputAlign="center"
              v-model="maxPrice"
            ></up-input>
          </view>
        </view>
        <view class="popup-filter">
          <view class="popup-title">品牌</view>
          <view class="brand-list">
            <view
              class="brand-item"
              :class="{ active: selectBrand.includes(brand.id) }"
              v-for="(brand, index) in brands"
              :key="index"
              @click="onBrandTap(brand.id)"
              >{{ brand.name }}
            </view>
          </view>
        </view>

        <view class="popup-filter-bottom">
          <up-button
            :customStyle="{ width: '160rpx' }"
            text="重置"
            @click="onResetFilter"
          ></up-button>
          <up-button
            :customStyle="{ width: '160rpx' }"
            type="primary"
            text="确定"
            @click="onConfirmFilter"
          ></up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { onReachBottom } from "@dcloudio/uni-app";
import { goodsList } from "@/common/apis/goods.js";
import { brandList } from "@/common/apis/brand.js";
import { useStore } from "vuex";

const store = useStore();

const priceSort = ref(true);
const numberSort = ref(true);

const sortList = ref(["id", "sale_price", "sale_number"]);

watch(
  () => priceSort.value,
  (newVal) => {
    if (newVal) {
      sortList.value[1] = "sale_price";
    } else {
      sortList.value[1] = "-sale_price";
    }
    getProductData();
  }
);

watch(
  () => numberSort.value,
  (newVal) => {
    if (newVal) {
      sortList.value[2] = "sale_number";
    } else {
      sortList.value[2] = "-sale_number";
    }
    getProductData();
  }
);

const popupShow = ref(false);
const brands = ref([]);
const selectBrand = ref([]);

const productList = ref([]);
const keyword = ref("");
const filterSort = ref("-price");
const minPrice = ref("");
const maxPrice = ref("");
const page = ref(1);
const limit = ref(6);
const category = ref("");
const totalPage = ref(0);
const loadStatus = ref("nomore");

const props = defineProps({
  type: String,
  keyword: String,
  categorizeId: Number,
  categorizeName: String,
  brandId: String,
  brandName: String,
  supplierId: String,
  supplierName: String,
});

function onScanCode() {
  // 调起条码扫描
  uni.scanCode({
    scanType: ["barCode"],
    success: function (res) {
      keyword.value = res.result;
      getProductData();
    },
    fail: function (err) {
      console.log(err);
      uni.showToast({
        title: "识别失败",
        icon: "error",
      });
    },
  });
}
function onSortChange(type) {
  if (type === "price") {
    filterSort.value = filterSort.value == "price" ? "-price" : "price";
  } else if (type === "sale") {
    filterSort.value = filterSort.value == "sale" ? "-sale" : "sale";
  }
  page.value = 1;
  getProductData();
}
function onSearch() {}

function onBrandTap(id) {
  if (selectBrand.value.includes(id)) {
    const index = selectBrand.value.findIndex((i) => i == id);
    selectBrand.value.splice(index, 1);
  } else {
    selectBrand.value.push(id);
  }
}
function onMoreFilter() {
  popupShow.value = !popupShow.value;
}
function onResetFilter() {
  minPrice.value = "";
  maxPrice.value = "";
  selectBrand.value = [];
}

function onConfirmFilter() {
  popupShow.value = false;

  getProductData();
}
function handleToGoodsDetail(row) {
  uni.navigateTo({
    url: "/src/pages/goods/detail?id=" + row.id,
  });
}
async function getBrandData() {
  const response = await brandList();
  if (response) {
    brands.value = response;
  }
}
async function getProductData() {
  uni.showLoading({ title: "加载中" });
  const response = await goodsList({
    search: keyword.value,
    page: page.value,
    size: limit.value,
    category: category.value,
    ordering: JSON.stringify(sortList.value),
    brand__in: selectBrand.value.join(","),
    sale_price__gte: minPrice.value,
    sale_price__lte: maxPrice.value,
    supplier_id: props.supplierId,
    subject__in: store.getters.formatSubjectList.map((i) => i.id).join(","),
  });
  if (response) {
    // 总页数
    productList.value =
      page.value == 1
        ? response.records
        : productList.value.concat(response.records);
    totalPage.value = response.total_page;
    loadStatus.value =
      page.value >= response.total_page ? "noremo" : "loadmore";
  }
  uni.hideLoading();
}

onMounted(() => {
  if (props.type === "search") {
    uni.setNavigationBarTitle({
      title: "商品搜索",
    });
    keyword.value = props.keyword;
  } else if (props.type === "categorize") {
    uni.setNavigationBarTitle({
      title: props.categorizeName,
    });
    category.value = props.categorizeId;
  } else if (props.type == "brand") {
    uni.setNavigationBarTitle({
      title: props.brandName,
    });
    selectBrand.value.push(Number(props.brandId));
  } else if (props.type == "coupon") {
    const titles = [];
    if (props.supplierName) {
      titles.push(props.supplierName);
    }
    if (props.categorizeName) {
      titles.push(props.categorizeName);
    }
    uni.setNavigationBarTitle({
      title: `优惠券商品(${titles.length ? titles.join("、") : "无限制"})`,
    });
    category.value = props.categorizeId;
  }
  getBrandData();
  getProductData();
});

onReachBottom(() => {
  if (page.value < totalPage.value) {
    page.value++;
    loadStatus.value = "loading";
    getProductData();
  }
});
</script>

<style scoped lang="scss">
.product {
  .m-l-10 {
    margin-left: 10rpx;
  }

  .m-r-10 {
    margin-right: 10rpx;
  }

  .product-top {
    padding: 20rpx 20rpx 0;
    background-color: #ffffff;
    height: 170rpx;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 1;

    .search {
      height: 70rpx;
      background-color: #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-radius: 8rpx;

      .search-left {
        padding: 0 10rpx;
      }
    }

    .filter {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .filter-item {
        width: calc(100% / 3);
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .filter-name {
          font-size: 30rpx;
        }
      }
    }
  }

  .product-main {
    margin-top: 190rpx;

    .product-list {
      padding: 20rpx;

      .product-item {
        margin-bottom: 20rpx;
      }
    }
  }

  .popup-main {
    padding: 40rpx 20rpx 140rpx;
    width: 600rpx;
    height: 100vh;
    box-sizing: border-box;
    background-color: #ffffff;
    position: relative;

    .popup-filter {
      margin-bottom: 30rpx;

      .popup-title {
        font-size: 30rpx;
        margin-bottom: 10rpx;
      }

      .popup-filter-price {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .line {
          width: 40rpx;
          height: 4rpx;
          background-color: #999999;
          margin: 0 20rpx;
        }
      }

      .brand-list {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .brand-item {
          padding: 6rpx 20rpx;
          background-color: #f0f0f0;
          color: #999999;
          font-size: 24rpx;
          border-radius: 8rpx;
          margin-right: 20rpx;
          margin-bottom: 20rpx;

          &.active {
            background-color: #3cb9ef;
            color: #ffffff;
          }
        }
      }
    }

    .popup-filter-bottom {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      border-top: 2rpx solid #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20rpx 0 40rpx;
    }
  }
}
</style>
